package cc.fs.zhihuapp.ui.activity.demo;

import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cc.fs.zhihuapp.R;
import cc.fs.zhihuapp.ui.activity.helper.BaseActivity;

/**
 * Created by fostion on 2015/10/8.
 * 这是WebViewdemo类用来尝试关于调用javastricty,关于网络定位的问题
 */
public class MyWebViewActivity extends BaseActivity {

    @InjectView(R.id.webview)
    WebView webview;

    WebSettings webSettings;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_webview_demo);
        ButterKnife.inject(this);

        setUpWebView();

    }

    private void setUpWebView() {
        webSettings = webview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webview.addJavascriptInterface(new JavaScriptInterface(this),"javaInterface");

        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return super.shouldOverrideUrlLoading(view, url);
            }
        });

        try {
//            InputStream htmlInputStream = getAssets().open("index.html");
//            String content = InputStreamToString(htmlInputStream);
//            webview.loadData(content,"text/html", "UTF-8");
            webview.loadUrl("file:///android_asset/index.html");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private String InputStreamToString(InputStream inputStream){
        String content = "";
        try {
            int count = 0;
            byte []buffer = new byte[1024];
            ByteArrayOutputStream outStream= new ByteArrayOutputStream();
            while((count = inputStream.read(buffer,0,1024)) != -1){
                outStream.write(buffer,0,count);
            }
            inputStream.close();
            content = new String(outStream.toByteArray(),"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    @Override
    public void handler(Message msg) {

    }

    public class JavaScriptInterface{

        private Context context;

        public JavaScriptInterface(Context context) {
            this.context = context;
        }

        //js中调用java的方法
        @JavascriptInterface
        public void show(){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    T("点击了网页的按钮");
                }
            });
        }
    }
}
